package com.marianhello.bgloc;

/**
 * Created by zilu on 2/26/2018.
 */

public class Util {
  public static double median(Double[] nums) {
    if(nums.length == 1) {
      return nums[0];
    }
    return sub(nums, 0, nums.length - 1, (nums.length + 1) / 2);
  }
  public  static double sqrt(double[] nums) {
    double x = nums[0];
    double y = nums[1];
    double z = nums[2];
    return Math.sqrt(x * x + y * y + z * z);
  }
  public  static double deltaSqrt(double[] nums, double[] nums2) {
    double x1 = nums[0];
    double y1 = nums[1];
    double z1 = nums[2];
    double x2 = nums2[0];
    double y2 = nums2[1];
    double z2 = nums2[2];
    return Math.sqrt((x1-x2) * (x1-x2) +(y1-y2) * (y1-y2)+ (z1-z2) * (z1-z2));
  }
  private static double sub(Double[] nums, int start, int end, int size) {
    int mid = (start + end) / 2;
    double pivot = nums[mid];
    int i = start - 1, j = end + 1;
    for (int k = start; k < j; k++) {
      if (nums[k] < pivot) {
        i++;
        double tmp = nums[i];
        nums[i] = nums[k];
        nums[k] = tmp;
      }
      else if (nums[k] > pivot) {
        j--;
        double tmp = nums[j];
        nums[j] = nums[k];
        nums[k] = tmp;
        k--;
      }
    }
    if (i - start + 1 >= size) {
      return sub(nums, start, i, size);
    }
    else if (j - start >= size) {
      return nums[j - 1];
    }
    else {
      return sub(nums, j, end, size - (j - start));
    }
  }
}
